//
//  HLBaseSessionViewController.m
//  YueYue
//
//  Created by hulu001 on 2023/6/13.
//

#import "HLBaseSessionViewController.h"
#import "HLIMKitSessionTableAdapter.h"
#import "HLIMKitInputViewImpl.h"
#import "HLIMKitEvent.h"
#import "HLIMKitMessageAudioContentView.h"
#import "HLIMKitSessionConfigurator.h"
#import "HLNIMUserCache.h"
#import "HLIMBackgroundView.h"

@interface HLBaseSessionViewController ()<HLIMKitInputViewDelegate>
@property (nonatomic, strong)   UIImageView *backgroundIMView;
@property (nonatomic, strong)   UIView *bottomView;
@property (nonatomic, strong)   HLIMKitSessionConfigurator *configurator;

@end

@implementation HLBaseSessionViewController

- (instancetype)initWithSession:(NIMSession *)session
{
    self = [super init];
    
    if (self) {
        self.session = session;
        [self addDelegates];
    }
    
    return self;
}

- (void)dealloc
{
    _tableView.dataSource = nil;
    _tableView.delegate = nil;
    
    [NSNotificationCenter.defaultCenter removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [NSNotificationCenter.defaultCenter removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [NSNotificationCenter.defaultCenter removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
    
    [self removeDelegates];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(appDidEnterBack)
                                               name:UIApplicationDidEnterBackgroundNotification
                                             object:nil];
    
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(appWillResignActive)
                                               name:UIApplicationWillResignActiveNotification
                                             object:nil];
    
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(appWillEnterForeground)
                                               name:UIApplicationWillEnterForegroundNotification
                                             object:nil];
}

- (void)initSubviews
{
    [super initSubviews];
    
    // Do any additional setup after loading the view.
    [self setupTableView];
    [self setupInputView];
    // 导航栏
    [self setupNav];
    
    //背景
    self.backgroundIMView = [[UIImageView alloc] initWithFrame:self.view.frame];
    _backgroundIMView.image = UIImageMake(@"session_background");
    _backgroundIMView.contentMode = UIViewContentModeScaleAspectFill;
    _backgroundIMView.layer.masksToBounds = YES;
    [self.view insertSubview:self.backgroundIMView atIndex:0];
}

#pragma mark - <添加网易云信代理>

- (void)addDelegates
{
    [NIMSDK.sharedSDK.chatManager addDelegate:self];
    [NIMSDK.sharedSDK.mediaManager addDelegate:self];
    [NIMSDK.sharedSDK.systemNotificationManager addDelegate:self];
    [NIMSDK.sharedSDK.conversationManager addDelegate:self];
}

- (void)removeDelegates
{
    [NIMSDK.sharedSDK.chatManager removeDelegate:self];
    [NIMSDK.sharedSDK.mediaManager removeDelegate:self];
    [NIMSDK.sharedSDK.systemNotificationManager removeDelegate:self];
    [NIMSDK.sharedSDK.conversationManager removeDelegate:self];
}

#pragma mark - <UI>

- (void)setupNav
{
    HLIMKitTitleView *titleView = (HLIMKitTitleView *)self.navigationItem.titleView;
    if (!titleView || ![titleView isKindOfClass:[HLIMKitTitleView class]])
    {
        titleView = [[HLIMKitTitleView alloc] initWithFrame:CGRectZero];
        self.navigationItem.titleView = titleView;
        self.imTitleView = titleView;
        
        [HLNIMUserCache.shareInstance userInfor:self.session.sessionId completion:^(NIMUser * _Nonnull user) {
            NSString *nickName = user.userInfo.nickName;
            titleView.titleLabel.text = nickName.length>5?[[nickName substringToIndex:5] stringByAppendingString:@"..."]:nickName;
            [titleView.avatarView sd_setBackgroundImageWithURL:[NSURL URLWithString:user.userInfo.thumbAvatarUrl] forState:UIControlStateNormal placeholderImage:[HLUIHelper avatarPlaceholder]];
        }];
    }

}

- (void)setupTableView
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.titleView.bottom, self.view.width, self.view.height - self.titleView.bottom) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.tableView.backgroundColor = UIColorClear;
//    self.tableView.contentInsetTop = IM_Height_NavBar;
    [self.view addSubview:self.tableView];
}

- (void)setupInputView
{
    if (self.disableInputView) {
        return;
    }
    self.sessionInputView = [HLIMKitInputViewImpl.alloc initWithFrame:CGRectMake(0, 0, self.view.width, 56 * 4) config:self.sessionConfig];
    self.sessionInputView.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.sessionInputView setActionDelegate:self];
    [self.sessionInputView setDelegate:self];
    [self.view addSubview:self.sessionInputView.view];
    if ([QMUIHelper isNotchedScreen]) {
        self.bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = UIColorWhite;
        [self.view addSubview:_bottomView];
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.mas_equalTo(0);
            make.height.mas_equalTo(34);
        }];
    }
    
    
}

- (void)setupConfigurator
{
    _configurator = [HLIMKitSessionConfigurator.alloc init];
    [_configurator setup:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.interactor onViewWillAppear];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_sessionInputView endEditing:YES];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.interactor onViewDidDisappear];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    [self.interactor resetLayout];
    [self setupNav];
}

#pragma mark - 监听

/// APP 已经进入后台
- (void)appDidEnterBack
{
    [self.interactor onApplicationDidEnterBack];
}

/// APP 将要挂起
- (void)appWillResignActive
{
    
}

/// APP 将要恢复前台
- (void)appWillEnterForeground
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 返回前台活跃状态后 刷新数据
        [self.interactor onApplicationDidBecomeActive];
    });
}

- (id<HLIMSessionConfig>)sessionConfig
{
    return nil;
}

- (void)changeCustomHeight:(NSInteger)height
{
    [self.interactor changeHeaderHeight:height];
}

// 底部View
- (void)changeCustomFooterHeight:(NSInteger)height
{
    [self.interactor changeFooterHeight:height];
}

#pragma mark - 消息接口

- (void)sendMessage:(id)message
{
    
}

- (void)sendMessage:(id)message completion:(void (^)(NSError * _Nonnull))completion
{
    [NIMSDK.sharedSDK.chatManager sendMessage:message toSession:self.session completion:completion];
}

#pragma mark - 操作接口

- (void)uiAddMessages:(NSArray *)messages
{
    // 向下追加新消息，过滤替换音视频显示文案
    [self.interactor addMessages:messages];
}

- (void)uiInsertMessages:(NSArray *)messages callback:(void (^ _Nullable)(id _Nonnull))callback
{
    // 向上加载历史消息，过滤替换音视频显示文案
    [self.interactor insertMessages:messages callback:callback];
}

- (HLIMKitMessageModel *)uiDeleteMessage:(NIMMessage *)message
{
    return [self.interactor deleteMessage:message];
}

- (HLIMKitMessageModel *)uiUpdateMessage:(NIMMessage *)message
{
    return [self.interactor updateMessage:message];
}

- (void)uiClearAllMessages
{
    [self.interactor clearAllMessages];
}

- (void)uiCheckReceipts:(NSArray<NIMMessageReceipt *> *)receipts
{
    [self.interactor checkReceipts:receipts];
}

#pragma mark - 排版

- (void)scrollToBottom:(BOOL)animated
{
    [self.interactor scrollToBottom:animated];
}

#pragma mark - <网易云信SDK>

#pragma mark - <NIMConversationManagerDelegate>

- (void)onSystemNotificationCountChanged:(NSInteger)unreadCount
{
    
}

/// 清空全部消息
- (void)messagesDeletedInSession:(NIMSession *)session
{
    if ([session.sessionId isEqualToString:self.session.sessionId]) {
        // 清空了当前会话
        [self uiClearAllMessages];
    }
}

- (void)allMessagesClearedInSession:(NIMSession *)session step:(NIMClearMessagesStatus)step
{
    if ([session.sessionId isEqualToString:self.session.sessionId]) {
        // 清空了当前会话
        [self uiClearAllMessages];
    }
}

- (void)onRecvAllRemoteMessagesInSessionDeleted:(NIMSessionDeleteAllRemoteMessagesInfo *)info
{
}

#pragma mark - <NIMChatManagerDelegate>

- (void)willSendMessage:(NIMMessage *)message
{
    // 将要发送消息
    [self uiAddMessages:@[message]];
}

- (void)sendMessage:(NIMMessage *)message didCompleteWithError:(NSError *)error
{
    // 消息已经发送 成功/失败
    if (error) {
        [self uiUpdateMessage:message];
    } else {
        if (message.messageType == NIMMessageTypeVideo) {
            NIMVideoObject *videoObject = (NIMVideoObject *)message.messageObject;
            if (![NSFileManager.defaultManager fileExistsAtPath:videoObject.coverPath]) {
                [NIMSDK.sharedSDK.resourceManager download:videoObject.coverUrl filepath:videoObject.coverPath progress:^(float progress) {
                } completion:^(NSError * _Nullable error) {
                    [self uiUpdateMessage:message];
                    [NIMSDK.sharedSDK.conversationManager markAllMessagesReadInSession:self.session completion:^(NSError * _Nullable error) {
                        if (error) {
                        }
                    }];
                }];
            } else {
                [self uiUpdateMessage:message];
            }
        } else {
            [self uiUpdateMessage:message];
            [NIMSDK.sharedSDK.conversationManager markAllMessagesReadInSession:self.session completion:^(NSError * _Nullable error) {
                if (error) {
                }
            }];
        }
    }
}

- (void)onRecvMessageReceipts:(NSArray<NIMMessageReceipt *> *)receipts
{
    NSMutableArray *handledReceipts = [[NSMutableArray alloc] init];
    for (NIMMessageReceipt *receipt in receipts) {
        if ([receipt.session isEqual:self.session])
        {
            [handledReceipts addObject:receipt];
        }
    }
    if (handledReceipts.count)
    {
        /// 收到已读回执
        [self.interactor checkReceipts:receipts];
    }
}

- (void)onRecvMessages:(NSArray<NIMMessage *> *)messages
{
    
    for (NIMMessage *msg in messages) {
        if (msg.messageType != 100) {
            [self uiAddMessages:@[msg]];
            [self markRead:YES];
        }
    }
}

/// 监听消息撤回
- (void)onRecvRevokeMessageNotification:(NIMRevokeMessageNotification *)notification {
    
}

#pragma mark - IMKitInputViewActionDelegate

- (void)onTextChanged:(id)sender {}

- (void)onSendText:(NSString *)text
           atUsers:(NSArray *)atUsers
{}

- (void)onSelectChartlet:(NSString *)chartletId
                 catalog:(NSString *)catalogId
{}

- (void)onCancelRecording {}

- (void)onStopRecording {}

- (void)onStartRecording {}

- (void)onTapMoreBtn:(id)sender {}

- (void)onTapEmoticonBtn:(id)sender{}

- (void)onTapVoiceBtn:(id)sender {}

- (void)onTapMoreItem:(nonnull HLIMKitInputMoreItem *)moreItem {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
    [self performSelector:moreItem.selector];
#pragma clang diagnostic pop
}


#pragma mark - IMKitInputViewDelegate

- (void)didChangeInputHeight:(CGFloat)inputHeight
{
    [self.interactor changeLayout:inputHeight];
}

- (void)recordBeginTouch
{
    // 调用SDK开始录音API
}

- (void)recordFinishInButton
{
    // 调用SDK结束录音API
}

- (void)recordDragToOut
{
    // UI显示松开取消的提示
}

- (void)recordDragBackToButton
{
    // 关闭松开取消提示 继续显示录音计时弹窗
}

- (void)recordFinishOutButton
{
    // 调用SDK取消录音API
}

#pragma mark - IMKitSessionInteractorDelegate

- (void)didPullUpMessageData {
    
}

- (void)didFetchMessageData {
    [self.tableView reloadData];
}

- (void)didRefreshMessageData {}

- (void)didReadBottomMessage {}

- (void)didRecievedBottomNewMessage:(NSInteger)messagesCount {}

#pragma mark - IMMessageCellDelegate

- (BOOL)onTapCell:(HLIMKitEvent *)event
{
    if ([event.gestureName isEqualToString:HLIMKitGestureTouchUpInside]) {
        if ([event.eventName isEqualToString:HLIMKitEventNameTapAudio])
        {   // 播放音频
            if (NIMSDK.sharedSDK.mediaManager.isPlaying) {
                
                BOOL isCurrentMessagePlaying = [HLIMKitAudioCenter.sharedCenter isPlayingMessage:event.messageModel.message];
                
                [HLIMKitAudioCenter.sharedCenter stop];
                
                if (!isCurrentMessagePlaying) {
                    // 如果不是重复点击正在播放的语音
                    // 当前点击的event.messageModel.message是一条新语音，则播放
                    [HLIMKitAudioCenter.sharedCenter play:event.messageModel.message];
                    [NIMSDK.sharedSDK.mediaManager seek:event.messageModel.seekTime];
                }
                
            } else {
                
                if (event.messageModel.seekTime <= 0.01) {
                    [HLIMKitAudioCenter.sharedCenter play:event.messageModel.message];
                } else {
                    NSTimeInterval seek = event.messageModel.seekTime;
                    [HLIMKitAudioCenter.sharedCenter play:event.messageModel.message];
                    [NIMSDK.sharedSDK.mediaManager seek:seek];
                    event.messageModel.seek = seek;
                    event.messageModel.seekTime = seek;
                }
            }
        } else if ([event.eventName isEqualToString:HLIMKitEventNameTapAudioPlain]) {
            // 点击了语音的文本
            [QMUITips showSucceed:[NSString stringWithFormat:@"点击了语音文本 \n %@", event.messageModel.message.localExt[@"plain"]]];
        }
    }
    return YES;
}

- (BOOL)onLongPressCell:(NIMMessage *)message inView:(UIView *)view
{
    BOOL handle = NO;
    NSArray *items = [self menusItems:message];
    if ([items count] ) {
        UIMenuController *controller = [UIMenuController sharedMenuController];
        controller.menuItems = items;
        _messageForMenu = message;
        [controller setTargetRect:view.bounds inView:view];
        [controller setMenuVisible:YES animated:YES];
        handle = YES;
    }
    return handle;
}

- (BOOL)onTapAvatar:(NIMMessage *)message
{
    return YES;
}

- (BOOL)onLongPressAvatar:(NIMMessage *)message
{
    return YES;
}

- (void)onRetryMessage:(NIMMessage *)message
{
    
}

#pragma mark - Private

- (void)refreshMessages {
    [self.interactor resetMessages:^(NSError * _Nonnull error) {
        
    }];
}

- (void)loadNewMessgaes
{
    // 返回前台活跃状态后 刷新数据
    [self.interactor onApplicationDidBecomeActive];
}

- (void)refreshBackgroundImage:(UIImage *)image url:(NSString *)url
{
//    if (self.backgroundIMView) {
//        self.backgroundIMView.backView.image = image;
//    } else {
//        self.backgroundIMView = [[HLIMBackgroundView alloc] initWithFrame:self.view.bounds];
//        self.backgroundIMView.backView.image = image;
//        [self.view insertSubview:self.backgroundIMView atIndex:0];
//    }
//    self.tableView.backgroundColor = UIColorClear;
//    if (url.length > 0) {
//        [self.backgroundIMView.backView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:image];
//    }
}

- (void)markRead:(BOOL)needSendReceipet
{
    [self.interactor markRead:needSendReceipet];
}

- (void)changeLeftBarBadge:(NSInteger)unreadCount
{
}

#pragma mark - 气泡长按的菜单选项

- (NSArray *)menusItems:(NIMMessage *)message
{
    NSMutableArray *items = [NSMutableArray array];
    
    BOOL copyText = NO;
    
    if (message.messageType == NIMMessageTypeText)
    {
        copyText = YES;
    }
    
    if (copyText) {
        [items addObject:[[UIMenuItem alloc] initWithTitle:@"复制"
                                                    action:@selector(copyText:)]];
    }
    
    return items;
    
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    NSArray *items = [[UIMenuController sharedMenuController] menuItems];
    for (UIMenuItem *item in items) {
        if (action == [item action]){
            return YES;
        }
    }
    return NO;
}

- (void)copyText:(id)sender
{
    NIMMessage * message = [self messageForMenu];
    if (message.text.length) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        [pasteboard setString:message.text];
    }
}

- (void)deleteMsg:(id)sender
{
    
}

- (void)revokeMsg:(id)sender
{
    
}

- (void)reportMsg:(id)sender
{
    
}

- (NSArray<HLIMKitMessageModel *> *)allDatas
{
    return self.interactor.items;
}

- (void)multiSelectMsgs:(id)sender
{
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.sessionInputView refreshStatus:HLIMInputStatusNone];
    [self.view endEditing:YES];
}


@end
